﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using Datalib;

namespace Host
{
    class HostMessageService : IHostFunctions
    {
        private static readonly List<IClientFunctions> subscribers = new List<IClientFunctions>();

        public void connect()
        {
            IClientFunctions callback = OperationContext.Current.GetCallbackChannel<IClientFunctions>();
            if (!subscribers.Contains(callback))
            {
                subscribers.Add(callback);
                Console.WriteLine("New client connected");
            }
        }

        public void disconnect()
        {
            IClientFunctions callback = OperationContext.Current.GetCallbackChannel<IClientFunctions>();
            if (subscribers.Contains(callback))
            {
                subscribers.Remove(callback);
                Console.WriteLine("client disconnected");
            }
        }

        public void send(ChatMessage cm)
        {
            List<IClientFunctions> subscribersToDelete = new List<IClientFunctions>();
            IClientFunctions callback = OperationContext.Current.GetCallbackChannel<IClientFunctions>();
            foreach (IClientFunctions client in subscribers)
            {
                if (client != callback)
                {
                    try
                    {
                        client.ShowMessage(cm.Name + ":\t" + cm.Message);
                    }
                    catch(Exception e)
                    {
                        subscribersToDelete.Add(client);
                        Console.WriteLine("Client lost connection" + e.Message);
                    }
                }
            }
            foreach (IClientFunctions client in subscribersToDelete)
            {
                if (subscribers.Contains(client))
                {
                    subscribers.Remove(client);
                }
            }
        }
    }
}